extends Sprite2D

@export var fog_width:int
@export var fog_height:int

var fog_image : Image
var fog_texture : ImageTexture

var current_image:Image
var current_texture : ImageTexture

@export var light_texture : Texture2D

@export var player : Node2D
@export var firePoins : Node2D


var light_image : Image
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	fog_image = Image.create(fog_width, fog_height, false, Image.FORMAT_RGBA8)
	fog_image.fill(Color.WHITE)
	fog_texture = ImageTexture.create_from_image(fog_image)
	texture = fog_texture
	current_image = fog_image.duplicate()
	current_texture = fog_texture.duplicate()
	material.set_shader_parameter("current_texture", current_texture)
	light_image = light_texture.get_image()
	update_fog()
	pass # Replace with function body.

func update_fog() -> void:
	var player_postion = player.global_position + Vector2(fog_width,fog_height)/2
	player_postion -= Vector2(light_image.get_size())/2
	player_postion.y -= 8
	fog_image.blend_rect(light_image, Rect2i(Vector2.ZERO,light_image.get_size()),player_postion)
	fog_texture.update(fog_image)
	
	#亮光部分
	current_image.fill(Color.WHITE)
	current_image.blend_rect(light_image, Rect2i(Vector2.ZERO,light_image.get_size()),player_postion)
		#遍历 firePoins
	for i in range(firePoins.get_child_count()):
		var firePoins_child = firePoins.get_child(i)
		if firePoins_child.bfire == false:
			continue
		var firePoins_child_position = firePoins_child.global_position + Vector2(fog_width,fog_height)/2
		firePoins_child_position-= Vector2(light_image.get_size())/2
		current_image.blend_rect(light_image, Rect2i(Vector2.ZERO,light_image.get_size()),firePoins_child_position)

	current_texture.update(current_image)

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if player.moving :
		update_fog()
	pass
